#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import json


class DeviceType:

    def __init__(self):
        self.work_dir = os.path.dirname(os.path.realpath(__file__))
        self.code_root = self._get_config("code_root")
        self.xts_root = self._get_config("xts_root")
        self.devicetypes = self._get_config("devicetypes")
        self.modules = self._get_config("product_components")

    def _get_config(self, key):
        with open('config.json', 'r') as rf:
            mydict = json.load(rf)
            return mydict.get(key)

    def get_all_projects(self):
        cmd = "./get_projects.sh {}".format(self.xts_root)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        projects = ret.stdout.decode().strip().split('\n')
        print("len(projects)={}, projects={}".format(len(projects), projects))
        return projects

    def get_module_name_of_project(self, project_directory):
        gn_file = os.path.join(project_directory, "BUILD.gn")
        cmd = './get_module_name.sh {}'.format(gn_file)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        module_name = ret.stdout.decode().strip().split('\n')[0]
        if not module_name:
            print("error: cannot find part_name from {}".format(gn_file))
        return module_name

    def get_indent(self, cfg_file):
        cmd = "./get_indent.sh {}".format(cfg_file)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        indent = ret.stdout.decode().strip()
        return indent

    def is_dos_format(self, cfg_file):
        cmd = "./is_dos_format.sh {}".format(cfg_file)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        is_dos = ret.stdout.decode().strip()
        return is_dos

    def update_devicetype_to_json(self, cfg_file, devicetypes):
        print("File {} append {} to DeviceType".format(cfg_file, self.devicetypes))
        load_dict = {}
        with open(cfg_file, 'r') as rf:
            load_dict = json.load(rf)
            if load_dict.get("module"):
                if load_dict.get("module").get("deviceTypes"):
                    old_devicetypes = load_dict.get("module").get("deviceTypes")
                    for i in devicetypes:
                        if i not in old_devicetypes:
                            load_dict.get("module")["deviceTypes"].append(i)
                    # load_dict.get("module")["deviceTypes"].extend(devicetypes)
                elif load_dict.get("module").get("deviceType"):
                    old_devicetypes = load_dict.get("module").get("deviceType")
                    for i in devicetypes:
                        if i not in old_devicetypes:
                            load_dict.get("module")["deviceType"].append(i)
                    # load_dict.get("module")["deviceType"].extend(devicetypes)
                else:
                    print("error: cannot find device type field from {}".format(cfg_file))
            else:
                print("error: cannot find module member from {}".format(cfg_file))

        indent = int(self.get_indent(cfg_file))
        is_dos = bool(int(self.is_dos_format(cfg_file)))
        newline = ["\n", "\r\n"][is_dos]

        with open(cfg_file, 'w', newline=newline) as wf:
            wf.write(json.dumps(load_dict, indent=indent, ensure_ascii=False))

    def update_devicetype(self, project_directory):
        module_name = self.get_module_name_of_project(project_directory)
        if not module_name:
            return
        if module_name not in self.modules:
            print("info: {} not belong to this product".format(module_name))
            return
        config_list = [
            'entry/src/main/module.json', 'src/main/config.json', 'entry/src/config.json', 'entry/src/main/config.json',
            'src/main/module.json', 'application/src/main/module.json'
        ]

        for item in config_list:
            if os.path.exists(os.path.join(project_directory, item)):
                self.update_devicetype_to_json(os.path.join(project_directory, item), self.devicetypes)
                return

        print("error: cannot find config file in project {}".format(project_directory))

    def batch_update_devicetype(self):
        projects = self.get_all_projects()
        for project in projects:
            self.update_devicetype(project)


def main():
    dt = DeviceType()
    dt.batch_update_devicetype()


if __name__ == "__main__":
    sys.exit(main())
